package com.wyf.reggie.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wyf.reggie.Entity.R;
import com.wyf.reggie.Entity.User;
import com.wyf.reggie.Service.UserService;
import com.wyf.reggie.Util.ValidateCodeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
   private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request){
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            System.out.println("验证码："+code);
            stringRedisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            //request.getSession().setAttribute(phone,code);
            return R.success("手机验证码发送成功");
        }
        return R.error("短信发送失败");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpServletRequest request){
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //Object attribute = request.getSession().getAttribute(phone);
        String attribute = stringRedisTemplate.opsForValue().get(phone);
        if(attribute!=null&&attribute.equals(code)){
            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            if(user==null){
                user=new User();
                user.setPhone(phone);
                userService.save(user);
            }
            request.getSession().setAttribute("user",user.getId());
            stringRedisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登陆失败");
    }
}
